package com.oto.web.resource;

import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.oto.Constants;
import com.oto.DataStatus;
import com.oto.model.FlowDO;
import com.oto.model.IndexDO;
import com.oto.model.PackDO;
import com.oto.service.FlowService;
import com.oto.service.PMF;
import com.oto.service.PackService;
import com.oto.service.SearchService;
import com.oto.util.DateUtils;

/**
 * @author xueqiang.mi
 * @since 2011-1-16
 */
@Path("/index")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class IndexResource {
	@Autowired
	protected FlowService flowService;
	@Autowired
	protected PackService packService;
	@Autowired
	protected SearchService searchService;

	@GET
	@Path("pack/{number}")
	@Produces("text/plain;charset=UTF-8")
	public String indexPack(@PathParam("number") int number) {
		List<PackDO> list = packService.latestUnsettled(number);
		for (PackDO e : list) {
			Collection<String> keys = searchService.parse(e.getName());
			for (String key : keys) {
				processKey(Constants.TYPE_PACK, key, e.getId());
			}
			packService.setDataStatus(e.getId(), DataStatus.INDEXED);
		}
		return Constants.STATUS_DONE;
	}

	@GET
	@Path("phone/{number}")
	@Produces("text/plain;charset=UTF-8")
	public String indexPhone(@PathParam("number") int number) {
		List<FlowDO> list = flowService.latestUnsettled(number);
		for (FlowDO e : list) {
			Collection<String> keys = searchService.parse(e.getName());
			for (String key : keys) {
				processKey(Constants.TYPE_PHONE, key, e.getId());
			}
			flowService.setDataStatus(e.getId(), DataStatus.INDEXED);
		}
		return Constants.STATUS_DONE;
	}

	private void processKey(int type, String key, Long id) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(IndexDO.class);
			query.setFilter("type=" + type + " && key == :key");

			@SuppressWarnings("unchecked")
			Collection<IndexDO> c = (Collection<IndexDO>) query.execute(key);
			IndexDO indexDO;
			if (c != null && !c.isEmpty()) {
				indexDO = (IndexDO) c.toArray()[0];
				indexDO.getObjs().add(id);
			} else {
				indexDO = new IndexDO();
				indexDO.setKey(key);
				indexDO.getObjs().add(id);
				indexDO.setCrtDate(DateUtils.now());
				pm.makePersistent(indexDO);
			}
		} finally {
			pm.close();
		}
	}
}
